const { wechatUser } = require('../../schemas/usersSchema.js')
const { Avatar } = require('../../schemas')

const { createToken } = require('../../utils/jwt.js')
const Snowflake = require('../../utils/snowflake.js')
const { phoneRegex, encryptPhoneNumber } = require('../../utils')
const { error } = require('winston')

const snowflake = new Snowflake(1, 1)

function getLastFourDigits(phoneNumber) {
  // 确保手机号是一个字符串
  phoneNumber = String(phoneNumber)

  // 获取手机号后四位
  const lastFourDigits = phoneNumber.slice(-4)

  return lastFourDigits
}
// 微信小程序 登录注册
const Login = async (request, reply) => {
  const { phoneNo } = request.body || {}
  // if (!phoneRegex.test(phoneNo)) {
  //   return reply.code(400).send({
  //     error: '手机号为11位',
  //     message: '手机号不合法',
  //     data: null,
  //     code: reply.statusCode,
  //   })
  // }
  const nick = getLastFourDigits(phoneNo)
  const { password, nickname = '昵称_' + nick } = request.body || {}
  try {
    const userData = await wechatUser.findOne({ phoneNo })

    if (userData && userData.password !== password) {
      return reply.code(400).send({
        code: reply.statusCode,
        message: '密码或手机号不正确！',
        data: null,
        error: '密码或手机号不正确！',
      })
    }
    if (userData) {
      const token = await createToken({ phoneNo: userData.phoneNo })
      await wechatUser.updateOne(
        { _id: userData._id },
        { $inc: { loginCount: 1 } }
      )
      return reply.code(200).send({
        code: reply.statusCode,
        message: '登陆成功！',
        data: {
          token,
          avatars: userData.avatars,
          userNo: userData.userNo,
          roleName: userData.roleName,
          roleId: userData.roleId,
          nickname: userData.nickName,
          userPhoneNo: encryptPhoneNumber(userData.phoneNo),
          address: userData.address,
        },
      })
    } else {
      const avatarData = await Avatar.find()
      const { fileUrl } = snowflake.getRandomFile(avatarData)

      const userNo = snowflake.generateUserId()

      const userModel = new wechatUser({
        ...request.body,
        nickName: nickname,
        userNo,
        roleName: '普通用户',
        roleId: 10001,
        avatars: fileUrl,
        loginCount: 1,
      })
      const saveUser = await userModel.save()
      const token = await createToken({ phoneNo: saveUser.phoneNo })
      return reply.code(200).send({
        code: reply.statusCode,
        message: '注册成功',
        data: {
          token,
          avatars: fileUrl,
          userNo,
          nickname,
          roleName: '普通用户',
          roleId: 10001,
          userPhoneNo: encryptPhoneNumber(phoneNo),
        },
      })
    }
  } catch (error) {
    return reply.code(500).send({
      code: reply.statusCode,
      message: '服务器内部错误！',
      data: null,
      error: error,
    })
  }
}

// 更新 用户信息
const Updated = async (request, reply) => {
  const { userPhoneNo } = request.query
  console.log(request.body)

  try {
    const result = await wechatUser.findOneAndUpdate(
      { phoneNo: userPhoneNo },
      request.body,
      { new: true }
    )
    if (result) {
      return reply.code(200).send({
        code: reply.statusCode,
        message: '更新成功！',
        data: null,
        error: null,
      })
    } else {
      return reply.code(400).send({
        code: reply.statusCode,
        message: '更新失败！',
        data: null,
        error: '该用户不存在！',
      })
    }
  } catch (error) {
    console.log(error)
  }
}

// 获取 登录用户 详情
const Details = async (request, reply) => {
  const { userNo } = request.params
  const userData = await wechatUser.findOne({ userNo })
  if (userData) {
    return reply.code(200).send({
      data: userData,
      message: '',
      error: '',
      code: reply.statusCode,
    })
  } else {
    return reply.code(400).send({
      code: reply.statusCode,
      message: '该用户不存在！',
      data: null,
      error: '该用户不存在！',
    })
  }
}

// 注册 列表
const wechatList = async (request, reply) => {
  const userListData = await wechatUser
    .find({}, { _id: 0, __v: 0 })
    .sort({ createdAt: -1 })
  if (userListData) {
    return reply.code(200).send({
      message: 'success',
      error: null,
      data: userListData,
      code: reply.statusCode,
    })
  }
}

module.exports = {
  Login,
  Updated,
  Details,
  wechatList,
}
